package ch.simplix.android.rumbler;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Vibrator;

public class RumblerService extends Service {
	private LocalBinder localBinder = new LocalBinder();
	private Vibrator vibrator;
	private int latestPercent;
	private ModeOfOperation mode = ModeOfOperation.Motor;
	private boolean stop;
	public static final String PERCENT = "Percent";
	public static final String CANCEL = "Cancel";
	public static final String MODE_OF_OPERATION = "ModeOfOperation";

	/**
	 * @see Binder
	 */
	public class LocalBinder extends Binder {
		public RumblerService getService() {
			return RumblerService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return localBinder;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		this.vibrator = (Vibrator) this
				.getSystemService(Context.VIBRATOR_SERVICE);
		this.stop = false;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		int percent = intent.getExtras().getInt("Percent");
		boolean cancel = intent.getExtras().getBoolean("Cancel");
		if (cancel)
			this.cancel();
		else
			rumble(percent);
		ModeOfOperation mode = ModeOfOperation.valueOf(intent.getExtras()
				.getString("ModeOfOperation"));
		if (mode != null)
			this.mode = mode;

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.stop = true;
		this.cancel();
		this.vibrator = null;
	}

	public void setMode(ModeOfOperation mode) {
		if (mode != null)
			this.mode = mode;
	}

	/**
	 * Stops the current rumbling.
	 */
	public void cancel() {
		if (this.vibrator != null) {
			this.vibrator.cancel();
			this.latestPercent = 0;
		}
	}

	public void rumble(int percent) {
		if (this.stop||vibrator==null) {
			return;
		}
		if (percent > 100) {
			percent = 100;
		}
		if (percent < 0) {
			percent = 0;
		}
		if (this.latestPercent == percent) {
			return;
		}

		this.latestPercent = percent;
		this.vibrator.cancel();
		if (this.latestPercent == 0) {
			return;
		}
		if (this.latestPercent == 100) {
			this.vibrator.vibrate(new long[] { 0, 10000 }, 0);
		} else {
			int timeSlotsOn;
			int timeSlotsOff;
			if (mode == ModeOfOperation.Motor) {
				timeSlotsOn = (mode.timeSlotPercentile * percent);
				timeSlotsOff = (mode.timeSlotPercentile * 100 - timeSlotsOn);
			} else {
				timeSlotsOn = (mode.timeSlotPercentile * percent) + 30;
				timeSlotsOff = (mode.timeSlotPercentile * (percent / 100)) + 20;
			}
			this.vibrator.vibrate(new long[] { timeSlotsOff,
					timeSlotsOn / mode.timeSlotFraction }, 0);

		}
	}

}
